package com.ailargemodel.controller;

import com.ailargemodel.common.BaseResponse;
import com.ailargemodel.common.RedisLimiterManager;
import com.ailargemodel.common.utils.ResultUtil;
import com.ailargemodel.pojo.AIrequest;
import com.ailargemodel.pojo.Questtion;
import com.ailargemodel.pojo.User;
import com.ailargemodel.service.AIService;
import com.ailargemodel.service.UserService;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.github.pagehelper.PageInfo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

//解决前端 跨域的问题

@CrossOrigin("*")
@RestController
@RequestMapping("/AI")
@Slf4j
public class AIController {

    @Autowired
    private AIService aiService;

    @Autowired
    private RedisTemplate redisTemplate;
    
    @Autowired
    private UserService userService;

    @Autowired
    private RedisLimiterManager redisLimiterManager;

    private void setAiLimiter(User loginUser){
        redisLimiterManager.doRateLimit("AI_"+loginUser.getStudyId());
    }
    @PostMapping("/Inquire")

    public BaseResponse inquire(@RequestBody AIrequest ai) throws NoApiKeyException, InputRequiredException {
        User loginUser = userService.getLoginUser(ai.getSessionId());
        setAiLimiter(loginUser);
        BaseResponse inquire = aiService.Inquire(ai.getContext(), loginUser, ai.getGrade());
        return inquire;
    }

    // 翻译 -> 题目解读 -> 思路引导 -> 纠错 -> 质量评估 -> 问AI

    /**
     * AI 功能一 翻译
     * @param aIrequest
     * @return
     * @throws NoApiKeyException
     * @throws InputRequiredException
     */
    @PostMapping("/translate")
    public BaseResponse translateAi(@RequestBody AIrequest aIrequest) throws NoApiKeyException, InputRequiredException {
        User loginUser = userService.getLoginUser(aIrequest.getSessionId());
        setAiLimiter(loginUser);
        BaseResponse translate = aiService.translate(loginUser, aIrequest.getContext(),aIrequest.getGrade());
        return translate;
    }


    /**
     * AI 功能二 题目解读
     * @param aIrequest
     * @return
     * @throws NoApiKeyException
     * @throws InputRequiredException
     */
    @PostMapping("/unscramble")
    public BaseResponse unscrambleAi(@RequestBody AIrequest aIrequest) throws NoApiKeyException, InputRequiredException {
        User loginUser = userService.getLoginUser(aIrequest.getSessionId());
        setAiLimiter(loginUser);
        BaseResponse unscramble = aiService.unscramble(loginUser,aIrequest.getContext(),aIrequest.getGrade());
        return unscramble;
    }

    /**
     * AI 功能三 思路引导
     * @param aIrequest
     * @return
     * @throws NoApiKeyException
     * @throws InputRequiredException
     */
    @PostMapping("/guidance")
    public BaseResponse guidanceAi(@RequestBody AIrequest aIrequest) throws NoApiKeyException, InputRequiredException {
        User loginUser = userService.getLoginUser(aIrequest.getSessionId());
        setAiLimiter(loginUser);
        BaseResponse guidance = aiService.guidance(loginUser,aIrequest.getContext(),aIrequest.getGrade());
        return guidance;
    }

    /**
     * AI 功能四 代码纠错
     * @param aIrequest
     * @return
     * @throws NoApiKeyException
     * @throws InputRequiredException
     */
    @PostMapping ("/correction")
    public BaseResponse correntionAi(@RequestBody AIrequest aIrequest) throws NoApiKeyException, InputRequiredException {
        User loginUser = userService.getLoginUser(aIrequest.getSessionId());
        setAiLimiter(loginUser);
        BaseResponse correction = aiService.correction(loginUser,aIrequest.getContext(),aIrequest.getGrade());
        return correction;
    }

    /**
     * 代码 评估
     * @param aIrequest
     * @return
     * @throws NoApiKeyException
     * @throws InputRequiredException
     */
    @PostMapping("/evaluation")
    public BaseResponse evalutaionAi(@RequestBody AIrequest aIrequest) throws NoApiKeyException, InputRequiredException {
        User loginUser = userService.getLoginUser(aIrequest.getSessionId());
        setAiLimiter(loginUser);
        BaseResponse evaluation = aiService.evaluation(loginUser,aIrequest.getContext(),aIrequest.getGrade());
        return evaluation;
    }

    /**
     * AI 历史搜查的查询
     * @author 喜洋洋
     * @description 用于返回
     */
    @GetMapping("/history")
    public BaseResponse historyList(@RequestParam Integer pageSize,@RequestParam Integer pageNum, @RequestParam String studyId) {
//        设置 redis 的缓存 ,让每一个 用户看到的 都是不同的数据

//        每一个使用的key, 都要保证和别人的不冲突, 因为,在节省成本时, 我们整个项目可能都只有一个redis  所以 , 每一个 使用的Id, 要和其他的Id不同, 利于区分
//        systemId::modelId::functionId
//        my reids of key is 'AIassistant::AIHistory::studyId'

        String redisKey = String.format("AIassistant::AIHistory::"+studyId);

        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

        PageInfo<Questtion> pageinfoList= (PageInfo<Questtion>) redisTemplate.opsForValue().get(redisKey);
//        如果有缓存 , 就直接从缓存中取得 , 没有则查询数据库
        if (pageinfoList != null){
            return ResultUtil.sucess(pageinfoList);
        }
//       无缓存 查数据库
        PageInfo<Questtion> pageInfo = aiService.selectHistoryBystudyId(pageSize,pageNum,studyId);

        try {
//            设置一下 过期时间 为 2H
            valueOperations.set(redisKey,pageInfo,2L, TimeUnit.HOURS);
        } catch (Exception e) {
            log.error("redis set cache error ",e);
        }

        return ResultUtil.sucess(pageInfo);
    }

    @GetMapping("/addNewConversation")
    public BaseResponse addNewConversation(@RequestParam(defaultValue = "创建一个新的会话")  String addMsg, @RequestParam String sessionId) {
//        TODO 创建会话
        User loginUser = userService.getLoginUser(sessionId);
        return aiService.addNewConversation(loginUser,sessionId);
    }
}
